package practica02;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Eje10 {

	public static void main(String[] args) {
		MiVentana v = new MiVentana();
		v.Iniciar();
	}
}

class MiVentana extends JFrame implements ActionListener{
	
	private static final long serialVersionUID = -5154519517393117725L;
	private JTextField txt1;
	private JTextField txt2;	
	private JLabel lbl1;
	private JLabel lbl2;
	private JButton btn1;
	private JButton btn2;

	public MiVentana(){
		super("Farenheit a Celsius");
		
		lbl1 = new JLabel("Farenheit");
		txt1= new JTextField(20);
				
		lbl2 = new JLabel("Celsius");
		txt2= new JTextField(20);				
		txt2.setEditable(false);
		
		btn1 = new JButton("Convertir");
		btn1.addActionListener(this);
		
		btn2 = new JButton("Cerrar");
		btn2.addActionListener(this);
		
		FlowLayout fl = new FlowLayout();
		fl.setAlignment(FlowLayout.RIGHT);
		
		JPanel pf = new JPanel();
		pf.setLayout(fl);		
		pf.add(lbl1);
		pf.add(txt1);
		
		JPanel pc = new JPanel();		
		pc.setLayout(fl);
		pc.add(lbl2);
		pc.add(txt2);		
		
		JPanel pb = new JPanel();		
		pb.setLayout(fl);
		pb.add(btn1);		
		pb.add(btn2);
		
		Container panel= getContentPane();		
		panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
		panel.add(pf);
		panel.add(pc);		
		panel.add(pb);		
	}
	
	public void Iniciar(){
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		pack();
		setResizable(false);
		setVisible(true);
	}
	
	public void actionPerformed(ActionEvent e) {
		double tmp=0;
		boolean error=false;
		
		if(e.getSource() == btn1){
			try{
					tmp = Double.parseDouble(txt1.getText());
					error=false;
				}catch(NumberFormatException ex){
					error=true;
				}
			if(error){
				JOptionPane.showMessageDialog(this,"Datos no correctos", "Error", JOptionPane.WARNING_MESSAGE);
				txt2.setText("");
			}else{
				txt2.setText(Double.toString(Conversor.Celsius(tmp)));
			}
		}
		
		if(e.getSource() == btn2){
			dispose();
		}
	}	
}

class Conversor{
	
	public static double Celsius(double dato){
		return (5*(dato-32))/9;
	}	
}